<template>
    <div>
        <Tabs :value="tabStatus" @on-click="changeTabs">
            <TabPane label="全部订单" name="null"></TabPane>
            <TabPane label="待支付" name="0"></TabPane>
            <TabPane label="待接单" name="1"></TabPane>
            <TabPane label="待配票" name="2"></TabPane>
            <TabPane label="已配票" name="3"></TabPane>
            <TabPane label="已发货" name="4"></TabPane>
            <TabPane label="已完成" name="99"></TabPane>
            <TabPane label="已取消" name="-1"></TabPane>
            <TabPane label="已退款" name="-2"></TabPane>
        </Tabs>
        <SuperTable ref="table" path="/order/index" :params="params" :columns="columns" @on-selection-change="handleSelectionChange">
            <div slot="header-left">
                <Form ref="filter" :model="filter" inline>
                    <FormItem label="订单来源">
                        <Select v-model="filter.order_source" clearable style="width: 100px">
                            <Option value="1">APP</Option>
                            <Option value="2">微信小程序</Option>
                            <Option value="3">H5</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="配送方式">
                        <Select v-model="filter.delivery_type" clearable style="width: 100px">
                            <Option value="1">电子票</Option>
                            <Option value="2">快递送票</Option>
                            <Option value="3">现场取票</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="下单时间">
                        <DatePicker v-model="filter.created_at" type="daterange" style="width: 240px; vertical-align: top;" clearable></DatePicker>
                    </FormItem>
                    <Button type="primary" @click="handlFilter">筛选</Button>
                    <Button v-if="!showMore" style="margin-left: 20px;" @click="handleMore" icon="ios-arrow-dropright" type="dashed">更多搜索</Button>
                    <Button v-else style="margin-left: 20px;" @click="handleMore" icon="ios-arrow-dropdown" type="dashed">收起</Button>
                    <div v-show="showMore">
                        <FormItem label="搜索类型">
                            <RadioGroup v-model="filter.search_type" @on-change="handleChangeSearchType">
                                <Radio :label="0" border>模糊搜索</Radio>
                                <Radio :label="1" border>精准搜索</Radio>
                            </RadioGroup>
                        </FormItem>
                        <FormItem v-if="filter.search_type == 0" label="模糊搜索">
                            <Input v-model="filter.keywords" style="width:200px" clearable placeholder="订单号/商家单号/手机号" />
                        </FormItem>
                        <FormItem v-if="filter.search_type == 1" label="精准搜索">
                            <Button type="info" @click="showSkuModal = true">选择票品</Button>
                            <Tag type="border" closable color="primary" v-for="(item, index) in selectedSkus" :key="index" :name="item.spec_name" @on-close="handleUnSelect(item, index)">{{item.concert.name}} {{item.name}}</Tag>
                        </FormItem>
                    </div>
                </Form>
            </div>
            <div slot="page-left">
                <Button type="warning" :disabled="selectedOrders.length == 0" @click="batchDelivery">批量顺丰发货</Button>
                <Button type="warning" :disabled="selectedOrders.length == 0" @click="handleBatchChange">批量修改配票方式</Button>
                <Button type="error" :disabled="selectedOrders.length == 0" @click="batchRefund">批量申请退款</Button>
            </div>
        </SuperTable>

        <Modal title="订单发货" v-model="showModalDelivery" :width="380" @on-cancel="handleCancelDelivery">
            <Form ref="formDelivery" :model="formDelivery" :rules="rulesDelivery" :label-width="80">
                <FormItem label="地址信息：">
                    <div style="font-size: 13px;">
                        <div id="address">
                            <div>
                                <span>{{ formDelivery.order.buyer_name }}</span>
                                <span style="margin-left: 20px;">{{ formDelivery.order.phone }}</span>
                            </div>
                            <div>{{ formDelivery.order.area_titles }}{{ formDelivery.order.address }}</div>
                        </div>
                        <Button size="small" type="info" @click="handleCopy">复制</Button>
                    </div>
                </FormItem>
                <FormItem label="快递公司" prop="express_identify">
                    <Select v-model="formDelivery.express_identify" clearable>
                        <Option v-for="item in expresses" :value="item.identify" :key="item.identify">{{ item.name }}</Option>
                    </Select>
                </FormItem>
                <FormItem label="快递单号" prop="express_sn">
                    <Input v-model="formDelivery.express_sn" placeholder="请填写快递单号"></Input>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button :disabled="submiting" @click="handleCancelDelivery">取消</Button>
                <Button type="primary" :loading="submiting" @click="handleSubmitDelivery">提交</Button>
            </div>
        </Modal>

        <Modal
            :title="'已选择'+selectedOrders.length+'条，过滤后剩余'+confirmChangeOrders.length+'条可审核，注意：此操作为异步操作，需要一定执行时间，请耐心等待几秒后刷新页面！'"
            v-model="showChangeModal"
            :width="1200"
        >
            <Table :width="1170" :columns="columnsChange" :data="confirmChangeOrders"></Table>
            <Form ref="formChange" :model="formChange" :rules="rulesChange" :label-width="84" style="margin-top:10px">
                <FormItem label="配送方式：" prop="delivery_type" required>
                    <RadioGroup v-model="formChange.delivery_type" >
                        <Radio :label="2">自配送</Radio>
                        <Radio :label="3">现场取票</Radio>
                    </RadioGroup>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button :disabled="submiting" @click="handleCancelChange">关闭</Button>
                <Button type="primary" :loading="submiting" @click="handleSubmitChange">提交</Button>
            </div>
        </Modal>

        <Modal
        v-model="confirmDeliveryModal"
        :title="'已选择'+selectedOrders.length+'条，过滤后剩余'+confirmDeliveryOrders.length+'条可发货，注意：此操作为异步操作，需要一定执行时间！'"
        :width="1200"
        >
            <Table :width="1170" :columns="columnsDelivery" :data="confirmDeliveryOrders"></Table>
            <div slot="footer">
                <Button @click="confirmDeliveryModal = false">关闭</Button>
                <Button type="primary" @click="handleConfirmSfDelivery">提交</Button>
            </div>
        </Modal>

        <Modal
        v-model="confirmRefundModal"
        :title="'已选择'+selectedOrders.length+'条，过滤后剩余'+confirmRefundOrders.length+'条可申请退款，注意：此操作为异步操作，需要一定执行时间！'"
        :width="1300"
        >
            <Table :width="1270" :columns="columnsDelivery" :data="confirmRefundOrders"></Table>
            <div slot="footer">
                <Button @click="confirmRefundModal = false">关闭</Button>
                <Button type="primary" @click="handleConfirmBatchRefund">提交</Button>
            </div>
        </Modal>

        <Modal
            v-model="showSkuModal"
            title="选择商品"
            width="1200px"
            @on-cancel="handleCancelSelect"
        >
            <SkuSelect ref="skus" :multiple="true" status="all" :value="selectedSkus"></SkuSelect>
            <div slot="footer">
                <Button @click="handleCancelSelect">取消</Button>
                <Button type="primary" @click="handleSelectSku">提交</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import SuperTable from '@/components/utils/super-table.vue';
import TableRows from '@/components/utils/table-rows.vue';
import PoptipTable from '@/components/utils/poptip-table.vue';
import SkuSelect from '@/components/selector/sku-select.vue';
import { formatDate,copy } from '@/libs/tools.js';
export default {
    components: {
        SuperTable,
        TableRows,
        SkuSelect
    },
    data() {
        return {
            submiting: false,
            tabStatus: 'null',
            //更改配送方式
            showChangeModal: false,
            confirmChangeOrders: [],
            formChange: {
                order_sns: [],
                delivery_type: 2,
            },
            rulesChange: {
                delivery_type: [
                    {required: true, type: 'number', message: '请选择配送方式', trigger: 'change'}
                ]
            },
            columnsChange: [
                {
                    title: "序号",
                    type: "index",
                    align: "center",
                    width: 54
                },
                {
                    title: '订单信息',
                    minWidth: 120,
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',`订单号：${params.row.order_sn}`),
                            h('p',`商家单号：${params.row.partner_osn || '-'}`)
                        ])
                    }
                },
                {
                    title: '票档信息',
                    minWidth: 150,
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',`${params.row.project_name}`),
                            h('p',[
                                h('span',`${params.row.concert_name + '  ' + params.row.sku_name}` + '  '),
                                h('span', {style:{color:'red'}}, `${params.row.number}张`)
                            ]),
                        ])
                    }
                },
                {
                    title: '购买信息',
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',`委托价：${params.row.partner_sku_price}`),
                            h('p',[
                                h('Tag', {
                                    props: {
                                        color: params.row.delivery_type == 1 ? 'blue' : 'green'
                                    }
                                }, params.row.delivery_type == 1 ? '电子票' : '纸质票')
                            ]),
                        ])
                    }
                },
                {
                    title: '卖家&买家',
                    minWidth: 80,
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',params.row.partner ? params.row.partner.name : '-'),
                            h('p',`${params.row.user.phone || '-'}`)
                        ])
                    }
                },
                {
                    title: '配送方式',
                    width: 80,
                    key: 'delivery_type_text'
                },
                {
                    title: '操作',
                    width: 94,
                    render: (h, params) => {
                        return h('Button', {
                            props: {
                                size: 'small',
                                type: 'error'
                            },
                            on: {
                                click: () => {
                                    this.confirmDeliveryOrders.splice(params.index, 1);
                                }
                            }
                        }, '删除');
                    }
                }
            ],
            //批量退款申请
            confirmRefundOrders: [],
            confirmRefundModal: false,
            //顺丰批量发货
            confirmDeliveryOrders: [],
            confirmDeliveryModal: false,
            columnsDelivery: [
                {
                    title: "序号",
                    type: "index",
                    align: "center",
                    width: 54
                },
                {
                    title: '订单信息',
                    minWidth: 120,
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',`订单号：${params.row.order_sn}`),
                            h('p',`商家单号：${params.row.partner_osn || '-'}`)
                        ])
                    }
                },
                {
                    title: '票档信息',
                    minWidth: 150,
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',`${params.row.project_name}`),
                            h('p',[
                                h('span',`${params.row.concert_name + '  ' + params.row.sku_name}` + '  '),
                                h('span', {style:{color:'red'}}, `${params.row.number}张`)
                            ]),
                        ])
                    }
                },
                {
                    title: '购买信息',
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',`委托价：${params.row.partner_sku_price}`),
                            h('p',[
                                h('Tag', {
                                    props: {
                                        color: params.row.delivery_type == 1 ? 'blue' : 'green'
                                    }
                                }, params.row.delivery_type == 1 ? '电子票' : '纸质票')
                            ]),
                        ])
                    }
                },
                {
                    title: '卖家&买家',
                    minWidth: 80,
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',params.row.partner ? params.row.partner.name : '-'),
                            h('p',`${params.row.user.phone || '-'}`)
                        ])
                    }
                },
                {
                    title: '状态',
                    width: 80,
                    key: 'status_text'
                },
                {
                    title: '操作',
                    width: 94,
                    render: (h, params) => {
                        return h('Button', {
                            props: {
                                size: 'small',
                                type: 'error'
                            },
                            on: {
                                click: () => {
                                    this.confirmDeliveryOrders.splice(params.index, 1);
                                }
                            }
                        }, '删除');
                    }
                }
            ],
            //发货
            expresses: [],
            showModalDelivery: false,
            formDelivery: {
                order: {},
                order_sn: '',
                express_identify: '',
                express_sn: '',
            },
            rulesDelivery: {
                express_identify: [
                    {required: true, message: '请选择快递公司', trigger: 'change'}
                ],
                express_sn: [
                    {required: true, message: '请输入快递单号', trigger: 'blur'}
                ]
            },
            //搜索
            showMore: false,
            selectedSkus: [],
            showSkuModal: false,
            selectedOrders: [],
            filter: {
                search_type: 0,
                order_source: '',
                delivery_type: '',
                created_at: [],
                keywords: '',
            },
            params: {
                sale_mode: 'direct',
                pageSize: 10,
                status: null,
                created_at: [],
                keywords: '',
            },
            columns: [
                {
                    type: 'selection',
                    width: 50,
                    align: 'center'
                },
                {
                    title: '订单信息',
                    minWidth: 120,
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',`订单号：${params.row.order_sn}`),
                            h('p',[
                                h('span',`商家单号：${params.row.partner_osn || '-'}`),
                                h('span', {style:{color:'#fd9827'}}, params.row.order_partner ? '['+params.row.order_partner.status_text+']' : '')
                            ])
                        ])
                    }
                },
                {
                    title: '票档信息',
                    minWidth: 150,
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',`${params.row.project_name}`),
                            h('p',[
                                h('span',`${params.row.concert_name + '  ' + params.row.sku_name}` + '  '),
                                h('span', {style:{color:'red'}}, `${params.row.number}张`)
                            ]),
                        ])
                    }
                },
                {
                    title: '卖家&买家',
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',params.row.partner ? params.row.partner.name : '-'),
                            h('p',`${params.row.user.phone || '-'}`)
                        ])
                    }
                },
                {
                    title: '支付总额&商家总额',
                    minWidth: 80,
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',`支付总额：${params.row.real_amount}`),
                            h('p',`商家总额：${params.row.order_partner ? params.row.order_partner.partner_amount : '-'}`),
                        ])
                    }
                },
                {
                    title: '类型&配票方式',
                    render: (h, params) => {
                        let delivery_type_text = ''
                        if (params.row.delivery_type == 2){
                            delivery_type_text = params.row.order_partner ? params.row.order_partner.delivery_type_text : '快递送票'
                        }else{
                            delivery_type_text = params.row.delivery_type_text
                        }
                        return h(TableRows,[
                            h('p',[
                                h('Tag', {
                                    props: {
                                        color: params.row.delivery_type == 1 ? 'blue' : 'green'
                                    }
                                }, params.row.delivery_type == 1 ? '电子票' : '纸质票')
                            ]),
                            h('p', delivery_type_text),
                        ])
                    }
                },
                {
                    title: '下单时间&状态',
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',`${params.row.created_at}`),
                            h('p',`${params.row.status_text}`)
                        ])
                    }
                },
                {
                    title: "操作",
                    key: "action",
                    width: 250,
                    render: (h, params) => {
                        let btns = [
                            h("Button", {
                                props: {
                                    type: "error",
                                    size: "small"
                                },
                                on: {
                                    click: () => {
                                        this.$Modal.confirm({
                                            title: "操作提示:",
                                            content: "<p>是否确认支付此订单?</p>",
                                            onOk: () => {
                                                this.$ajax.post('/order/paid', {order_sn: params.row.order_sn}).then(res => {
                                                    this.$Message.success('操作成功');
                                                    this.$refs.table.init();
                                                }).catch(err => {
                                                    this.$Message.error(err.message || '操作失败');
                                                })
                                            }
                                        });
                                    }
                                }
                            }, "已支付"),
                            h("Button", {
                                style: {
                                    marginLeft: "5px"
                                },
                                props: {
                                    type: "error",
                                    size: "small"
                                },
                                on: {
                                    click: () => {
                                        this.$Modal.confirm({
                                            title: "操作提示:",
                                            content: "<p>是否确认退款此订单?</p>",
                                            onOk: () => {
                                                this.$ajax.post('/order/refunded', {order_sn: params.row.order_sn}).then(res => {
                                                    this.$Message.success('操作成功');
                                                    this.$refs.table.init();
                                                }).catch(err => {
                                                    this.$Message.error(err.message || '操作失败');
                                                })
                                            }
                                        });
                                    }
                                }
                            }, "已退款"),
                            h("Button", {
                                style: {
                                    marginLeft: "5px"
                                },
                                props: {
                                    type: "primary",
                                    size: "small"
                                },
                                on: {
                                    click: () => {
                                        this.$router.push({name: 'order_detail', query: {order_sn: params.row.order_sn}});
                                    }
                                }
                            }, "查看"),
                        ];
                        if (params.row.status == 3 && params.row.order_partner.delivery_type == 1){
                            btns.push(
                                h("Button", {
                                    style: {
                                        marginLeft: "5px"
                                    },
                                    props: {
                                        type: "warning",
                                        size: "small"
                                    },
                                    on: {
                                        click: () => {
                                            this.formDelivery.order = params.row;
                                            this.formDelivery.order_sn = params.row.order_sn;
                                            this.showModalDelivery = true;
                                        }
                                    }
                                }, "发货")
                            )
                        }
                        if (params.row.status > 0 && params.row.status != 99){
                            btns.push(
                                h("Button", {
                                    style: {
                                        marginLeft: "5px"
                                    },
                                    props: {
                                        type: "error",
                                        size: "small"
                                    },
                                    on: {
                                        click: () => {
                                            this.handleRefund(params.row);
                                        }
                                    }
                                }, "退款")
                            )
                        }
                        return h("div", btns);
                    }
                }
            ]
        }
    },
    mounted() {
        if (this.$route.query.status) {
            this.tabStatus = '3';
            this.filter.delivery_type = '2';
            this.params.delivery_type = '2';
            this.params.status = '3';
            this.$refs.table.init();
        }
        this.init();
    },
    methods: {
        init(){
            this.$ajax.get('/common/express/index').then(res => {
                this.expresses = res;
            }).catch(() => {
            })
        },
        changeTabs(e){
            this.params.status = (e === 'null') ? null : e;
            this.$refs.table.init();
        },
        handleSelectionChange(selections){
            this.selectedOrders = selections
        },
        handlFilter() {
            const { filter } = this;
            this.params.order_source = filter.order_source;
            this.params.delivery_type = filter.delivery_type;
            this.params.created_at = [formatDate(filter.created_at[0],'yyyy-MM-dd'),formatDate(filter.created_at[1],'yyyy-MM-dd')];
            this.params.keywords = filter.keywords;
            this.$refs.table.init();
        },
        //订单发货
        handleSubmitDelivery() {
            if(this.submiting) return false;
            this.$refs.formDelivery.validate((valid) => {
                if(valid) {
                    this.submiting = true;
                    let params = {
                        order_sn: this.formDelivery.order_sn,
                        express_identify: this.formDelivery.express_identify,
                        express_sn: this.formDelivery.express_sn
                    }
                    this.$ajax.post('/order/delivery/platform', params).then(res => {
                        this.$Message.success('操作成功');
                        this.submiting = false;
                        this.handleCancelDelivery();
                        this.$refs.table.init();
                    }).catch(err => {
                        this.submiting = false;
                        this.$Message.error(err.message || '操作失败');
                    })
                }
            })
        },
        handleCancelDelivery(){
            this.showModalDelivery = false;
            setTimeout(() => {
                this.formDelivery.order = {};
                this.formDelivery.order_sn = '';
                this.formDelivery.express_identify = '';
                this.formDelivery.express_sn = '';
            }, 300)
        },
        handleCopy() {
            let text = this.formDelivery.order.buyer_name +' '+ this.formDelivery.order.phone +' ' + this.formDelivery.order.area_titles + this.formDelivery.order.address;
            copy(text,() => {
                this.$Message.success('复制成功');
            },() => {
                this.$Message.error('复制失败');
            });
        },
        //顺丰批量发货
        batchDelivery(){
            this.confirmDeliveryModal = true;
            let _lists = [];
            this.selectedOrders.map(item =>{
                if (item.status == 3 && item.order_partner.delivery_type == 1){
                    _lists.push(item);
                }
            })
            this.confirmDeliveryOrders = _lists;
        },
        handleConfirmSfDelivery(){
            let order_sns = [];
            this.confirmDeliveryOrders.map(item => {
                order_sns.push(item.order_sn);
            })
            this.$ajax.post('/order/delivery/batch_sf', {order_sns:order_sns}).then(() => {
                this.$Message.success('操作成功');
                this.confirmDeliveryModal = false;
                setTimeout(() => {
                    this.$refs.table.reload();
                }, 2000)
            }).catch(err => {
                this.$Message.error(err.message || '操作失败');
            })
        },
        //批量更改配送方式
        handleBatchChange(){
            this.showChangeModal = true;
            let _lists = [];
            this.selectedOrders.map(item =>{
                if (item.delivery_type == 2 && item.status == 2){
                    _lists.push(item);
                }
            })
            this.confirmChangeOrders = _lists;
        },
        handleSubmitChange() {
            if(this.submiting) return false;
            this.$refs.formChange.validate((valid) => {
                if(valid) {
                    let order_sns = [];
                    this.confirmChangeOrders.map(item => {
                        order_sns.push(item.order_sn);
                    })
                    if (order_sns.length == 0){
                        this.$Message.error('无可操作数据');
                        return false;
                    }
                    let params = {
                        order_sns: order_sns,
                        delivery_type: this.formChange.delivery_type,
                    }
                    const msg = this.$Message.loading({
                        content: '正在提交',
                        duration: 0
                    });
                    this.submiting = true;
                    this.$ajax.post('/order/batch_change_delivery', params).then(() => {
                        msg();
                        this.$Message.success('操作成功');
                        this.submiting = false;
                        this.showChangeModal = false;
                        setTimeout(() => {
                            this.$refs.table.reload();
                        }, 2000)
                    }).catch(err => {
                        msg();
                        this.submiting = false;
                        this.$Message.error(err.message || '操作失败');
                    })
                }
            })
        },
        handleCancelChange(){
            this.showChangeModal = false;
            this.confirmChangeOrders = [];
            this.$refs.table.reload();
        },
        //批量申请退款
        handleRefund(order) {
            this.$Modal.confirm({
                title: "操作提示:",
                content: "<p>是否申请退款?</p>",
                onOk: () => {
                    this.confirmRefundOrders = [order]
                    this.handleConfirmBatchRefund();
                }
            });
        },
        batchRefund(){
            this.confirmRefundModal = true;
            let _lists = [];
            this.selectedOrders.map(item =>{
                if (item.status > 0 && item.status != 99){
                    _lists.push(item);
                }
            })
            this.confirmRefundOrders = _lists;
        },
        handleConfirmBatchRefund(){
            let order_sns = [];
            this.confirmRefundOrders.map(item => {
                order_sns.push(item.order_sn);
            })
            this.$ajax.post('/order/refund/batch_refund', {order_sns:order_sns}).then(() => {
                this.$Message.success('操作成功');
                this.confirmRefundModal = false;
                setTimeout(() => {
                    this.$refs.table.reload();
                }, 2000)
            }).catch(err => {
                this.$Message.error(err.message || '操作失败');
            })
        },
        //搜索相关
        handleChangeSearchType(){
            if (this.filter.search_type === 0){
                this.params.sku_ids = [];
                this.selectedSkus = [];
            }else{
                this.filter.keywords = '';
                this.params.keywords = '';
            }
        },
        handleCancelSelect(){
            this.showSkuModal = false;
        },
        handleSelectSku(){
            let res = this.$refs.skus.getCheckeds();
            let sku_ids = [];
            let _skus = [];
            res.map(item => {
                _skus.push(item);
                sku_ids.push(item.id);
            })
            this.selectedSkus = _skus;
            this.params.sku_ids = sku_ids;
            this.handleCancelSelect();
        },
        handleUnSelect(item,index){
            this.selectedSkus.splice(index, 1);
            let sku_ids = [];
            this.selectedSkus.map(item => {
                sku_ids.push(item.id);
            })
            this.params.sku_ids = sku_ids;
        },
        handleMore(){
            if (this.showMore == false){
                this.showMore = true;
            }else{
                this.showMore = false;
            }
        },
    }
}
</script>